/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chat.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author DoiPA
 */
public class DemoTCPServer {

    static ServerSocket ss;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnknownHostException, IOException {

        //Starting server
        int port = 4321;
        ss = new ServerSocket(port);
        Manager m = new Manager();
        System.out.println("Server is running!");

        //Each loop to accept a client
        while (true) {
            try {
                //Accept client
                Socket s = ss.accept();

                //Get client login
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                
                String clientName = br.readLine();
                //Check name with manager
                Camarero camarero= new Camarero(clientName, m, s);
                boolean added = m.addCamarero(camarero);
                PrintWriter pw = new PrintWriter(s.getOutputStream());
                if (added) {
                    new Thread(camarero).start();
                    pw.println("1");
                } else {                    
                    pw.println("0");
                }
                pw.flush();
            } catch (IOException ex) {
            }
        }
    }
}
